// #################################################

// ==UserScript==
// @name            Interface Moderateur v4 Multi Room
// @version         4.314.201401291841
var version =      '4.314.201401291841'
// @description     Interface pour les moderateur avec quelque fonction pour facilité la modération
// @match           http://www.gamingroom.tv/*
// @copyright       2014+, Djmemo
// ==/UserScript==

// #################################################

var debug = true;
var self = this;

this.message_debug = function(message){
    if(debug){
        console.log(message);
    };
};

var recherche_room = /room:\s([0-9])/igm
var resultat_room = recherche_room.exec($('script').text());
var room = resultat_room[1];

var recherche_admin_url = /admin_url:\s"(.*)",/igm
var resultat_admin_url = recherche_admin_url.exec($('script').text());
var admin_url = resultat_admin_url[1];

var scrollemulator_modo = true;
var full_screen = false;

self.message_debug('Interface Modo : room '+room);

// #################################################

this.interface_moderateur = function() {
    // Style
    $("head style:last").after('<link href="http://grtv.ralmn.fr/css/im-style.css" rel="stylesheet">');
    $("head style:last").after('<style type="text/css">.interface_modo_btn_info {margin-top:0px;} .show_streaminfo_active{background-color: #830404!important;}</style>');
    $("head style:last").after('<style type="text/css">#interface_modo_info{height:100%;width:100%;position:absolute;opacity:1;z-index:99;box-shadow:inset 0 0 200px #5f5f5f;-moz-box-shadow:inset 0 0 200px #5f5f5f;background-color: rgba(95, 95, 95, 0.75);}#interface_modo_info ul{color:#f2efea;margin-left:0;font-size:12px}#interface_modo_info ul img{margin-right:10px}#interface_modo_info ul i{font-size:16px;line-height:250%;color:#f2eeea;text-shadow:0 -1px 0 #000;display:block;height:40px;width:40px;float:left;text-align:center}#interface_modo_info ul li{height:40px;line-height:40px}#interface_modo_info ul li:nth-child(odd){background-color:#2d2d2d}#interface_modo_info ul li:nth-child(even){background-color:#3a3a3a}</style>');
    $("head style:last").after('<style type="text/css">#interface_modo_supprimer_message {margin: -3px 3px 0px 0px;z-index: 99;float: left;left: 0;top: 0;height: 17px;color: red;opacity: 0.5;text-shadow: 0 0 5px rgba(255, 0, 0, 0.5);}</style>');    
    $("head style:last").after('<style type="text/css">#chat_modo_forum {width: 100%;height: 400px;border: 0;} .im_remove{display: none!important;}</style>');
 
    // Bouton de l'interface
    $("#user-widget").append('<div style="position: absolute; top: 0; right: 80px; width: 40px; height: 40px;z-index: 99;color: #FFFFFF;font-size: 18px; line-height: 38px;text-align: center;background-color: #005544;" class="im-btn_onglet interface_modo_btn_info" id="interface_modo_config_info"><i class="fa fa-wrench"></i></div>');

    // Interface
    var html_interface_option = '\
    <div id="interface_modo_config" style="margin: 20px 0px 0px 0px; display: none;">\n\
        <ul class="im-nav im-nav-tabs" id="myTab_modo" style=" margin: 10px 15px -2px 15px; border: 0; background-color: #f5f5f5; border-radius: 5px 5px 0 0; ">\n\
            <li class="active" style=" background-color: rgba(0,0,0,0); border-radius: 5px 5px 0 0; ">\n\
                <a href="#options" data-toggle="tab">Options</a>\n\
            </li>\n\
            <li style=" background-color: rgba(0,0,0,0); border-radius: 5px 5px 0 0; ">\n\
                <a href="#chat_modo" data-toggle="tab">Chat</a>\n\
            </li>\n\
            <li style=" background-color: rgba(0,0,0,0); border-radius: 5px 5px 0 0; ">\n\
                <a href="#code_modo" data-toggle="tab">Code</a>\n\
            </li>\n\
            <i style="float: right; padding: 10px 15px;">Interface Beta v '+version+'</i>\n\
        </ul>\n\
        \n\
        <div class="im-tab-content" style=" border: none; border-radius: 0; padding: 0; margin: 0; ">\n\
            <div class="im-tab-pane active" id="options">\n\
                <div class="im-container" style="width: 100%;">\n\
                    <div class="im-well">\n\
                        <div class="im-row">\n\
                            <div class="im-col-md-6">\n\
                                <div class="im-breadcrumb-text">\n\
                                    <h4 class="im-caption">Option jeton</h4>\n\
                                </div>\n\
                                <div class="im-input-group">\n\
                                    <span class="im-input-group-btn">\n\
                                        <button class="im-btn im-btn-mini im-btn-primary" type="button" id="interface_modo_token" style="background-color: #1abc9c;border: 2px solid #1abc9c;color: #FFF;">Voir Jeton</button>\n\
                                        <button class="im-btn im-btn-mini im-btn-primary" type="button" id="interface_modo_token_valider" style="background-color: #1abc9c;border: 2px solid #1abc9c;color: #FFF;">Valider Jeton</button>\n\
                                    </span>\n\
                                    <input type="text" class="im-form-control" id="interface_modo_token_text" placeholder=" Ici voir ou insérer et valider le Jeton" style=" height: 36px; ">\n\
                                </div>\n\
                            </div>\n\
                            <div class="im-col-md-6">\n\
                                <div class="im-breadcrumb-text">\n\
                                    <h4 class="im-caption">Option recherche de mot</h4>\n\
                                </div>\n\
                                <div class="im-input-group">\n\
                                    <span class="im-input-group-btn">\n\
                                        <button class="im-btn im-btn-mini im-btn-primary" type="button" id="interface_modo_regex_pseudo_bouton" style="background-color: #1abc9c;border: 2px solid #1abc9c;color: #FFF;">Valider</button>\n\
                                    </span>\n\
                                    <input type="text" class="im-form-control" id="interface_modo_regex_pseudo" placeholder=" Mot à remplacer" style=" height: 36px; ">\n\
                                </div>\n\
                            </div>\n\
                        </div>\n\
                        <br />\n\
                        <div class="im-row">\n\
                            <div class="im-col-md-12">\n\
                                <div class="im-breadcrumb-text">\n\
                                    <h4 class="im-caption">Option divers</h4>\n\
                                </div>\n\
                                <div class="im-col-md-2">\n\
                                    <button type="button" class="im-btn im-btn-mini im-btn-primary" id="interface_modo_TrackpadScrollEmulator">\n\
                                        <span>Desactiver le Scroll</span>\n\
                                    </button>\n\
                                </div>\n\
                                <div class="im-col-md-2">\n\
                                    <button type="button" class="im-btn im-btn-mini im-btn-primary" id="interface_modo_add_remove_scrollbar">\n\
                                        <span>Cacher la ScrollBar</span>\n\
                                    </button>\n\
                                </div>\n\
                                <div class="im-col-md-2">\n\
                                    <button type="button" class="im-btn im-btn-mini im-btn-primary" id="interface_modo_full_screen">\n\
                                        <span>Activer le Full Screen</span>\n\
                                    </button>\n\
                                </div>\n\
                                <div class="im-col-md-2">\n\
                                    <button type="button" class="im-btn im-btn-mini im-btn-primary" id="interface_modo_nouveau_csrf_token">\n\
                                        <span>Nouveau token</span>\n\
                                    </button>\n\
                                </div>\n\
                            </div>\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
            </div>\n\
            <div class="im-tab-pane" id="chat_modo">\n\
                <div class="im-container" style="width: 100%;">\n\
                    <div class="im-well">\n\
                        <div class="im-row">\n\
                            <div class="im-col-md-12">\n\
                                <div class="im-breadcrumb-text">\n\
                                    <h4 class="im-caption">Chat du forum</h4>\n\
                                </div>\n\
                                <div class="im-well">\n\
                                    <iframe id="chat_modo_forum" src="http://forumpv.gamingroom.tv/index.php?taigachat/popup" scrolling="no"></iframe>\n\
                                </div>\n\
                            </div>\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
            </div>\n\
            <div class="im-tab-pane" id="code_modo">\n\
                <div class="im-container" style="width: 100%;">\n\
                    <div class="im-well">\n\
                        <div class="im-row">\n\
                            <div class="im-col-md-12">\n\
                                <div class="im-breadcrumb-text">\n\
                                    <h4 class="im-caption">Code pour le chat de la GRTV !</h4>\n\
                                </div>\n\
                                <div class="im-well" style=" overflow: overlay; height: 500px; ">\n\
                                    <iframe id="chat_modo_forum" src="http://192.168.1.10/grtv/ralmn/" scrolling="no" style=" height: 1500px; "></iframe>\n\
                                </div>\n\
                            </div>\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
            </div>\n\
        </div>\n\
        <script>\n\
            $(function () {\n\
                $(\'#myTab_modo a#options\').tab(\'show\')\n\
            })\n\
        </script>\n\
    </div>\n\
    ';
    $("#main-live").after(html_interface_option);
    $(".lives").after(html_interface_option);
    
    $("#interface_modo_token").click( function() {
        self.message_debug('Interface : click bouton token');
        $('#interface_modo_token_text').val($('#csrf_token').val());
    });

    $("#interface_modo_token_valider").click( function() {
        self.message_debug('Interface : click bouton token replace');
        $('#csrf_token').val($('#interface_modo_token_text').val());
    });
    
    $("#interface_modo_add_remove_scrollbar").click( function() {
        self.message_debug('Interface : click bouton add remove scrollbar');
        if($(".tse-scrollbar").hasClass( "im_remove" )){
            $( "div.tse-scrollbar" ).toggleClass("im_remove",false);
            $('#interface_modo_add_remove_scrollbar').text('Cacher la ScrollBar');
        }else{
            $( "div.tse-scrollbar" ).toggleClass("im_remove",true);
            $('#interface_modo_add_remove_scrollbar').text('Afficher la ScrollBar');
        }
    });

    $('#messages').on('click', '#interface_modo_supprimer_message', function () {
        var details_modal = $('.user-details-modal');
        var parent = $(this).parent();
        var message_infos = parent.data('message-infos');
        self.message_debug('Interface Modo : message_infos.message.id ' + message_infos.message.id);
        var parameters = JSON.stringify( {target: message_infos.message.id});
        self.commande_admin("delete_user_message", parameters);
    });

    $('#messages').on('mouseenter', '#interface_modo_supprimer_message', function () {
        scroll_start_stop("stop");
    });
    
    $('#messages').on('mouseleave', '#interface_modo_supprimer_message', function () {
        scroll_start_stop("start");
    });

    $("#interface_modo_regex_pseudo_bouton").click( function() {
        self.message_debug('Interface Modo : click bouton regex pseudo');
        regex_pseudo = RegExp($('#interface_modo_regex_pseudo').val(),"igm");
    });

    $("#interface_modo_TrackpadScrollEmulator").click( function() {
        self.message_debug('Interface : click bouton ScrollEmulator');
        scroll_start_stop("normale");
    });
    
    var full_screen_chat_height;
    var full_screen_tse_scroll_content_width;
    var full_screen_tse_scroll_content_height;
    var full_screen_messages_height;
    $("#interface_modo_full_screen").click( function() {
        if(full_screen){
            $('#interface_modo_config').fadeOut('fast');
            $('#interface_modo_config_info').removeClass('show_streaminfo_active');
            $(".clearboth").css("display", "");
            $(".followme").css("display", "");
            $(".ad-wide").css("display", "");
            $("#plannings").css("display", "");
            $("#krou-homepage").css("display", "");
            $(".replays").css("display", "");
            $(".modal fade").css("display", "");
            $("footer").css("display", "");
            $(".mini-preview").css("display", "");
            $(".two-third").css("display", "");
			$(".contenus-libres").css("display", "");
            $(".restrictwidth").css("max-width", "");
            $(".onethird").css({"width": "","left": "","display": "","position": ""});
            setTimeout(function(){
                $(".tse-scroll-content").css({"width": full_screen_tse_scroll_content_width, "height": full_screen_tse_scroll_content_height});
                $("#messages").css({"height": full_screen_messages_height});
                $("#chat").css({"height": full_screen_chat_height});
            },2000);
            $('#interface_modo_full_screen').text('Activer le Full Screen');
            full_screen = false;
        }else{
            full_screen_chat_height = $("#chat").css("height");
            full_screen_tse_scroll_content_width = $(".tse-scroll-content").css("width");
            full_screen_tse_scroll_content_height = $(".tse-scroll-content").css("height");
            full_screen_messages_height = $("#messages").css("height");
            $('#interface_modo_config').fadeOut('fast');
            $('#interface_modo_config_info').removeClass('show_streaminfo_active');
            $(".clearboth").css("display", "none");
            $(".followme").css("display", "none");
            $(".ad-wide").css("display", "none");
            $("#plannings").css("display", "none");
            $("#krou-homepage").css("display", "none");
            $(".replays").css("display", "none");
            $(".modal fade").css("display", "none");
            $("footer").css("display", "none");
            $(".mini-preview").css("display", "none");
            $(".two-third").css("display", "none");
			$(".contenus-libres").css("display", "none");
            $(".restrictwidth").css("max-width", "none");
            $("#chat").css("height", ($(window).height()-120)+"px");
			$(".onethird").css({"width": "100%","left": "0px","position": "fixed"});
            $(".tse-scroll-content").css({"width": "", "height": ($(window).height()-200)+"px"});
            $("#messages").css({"height": ($(window).height()-200)+"px"});
            $('#interface_modo_full_screen').text('Deactiver le Full Screen');
            full_screen = true;
        }
    });

    /*
        hauteur du chat
        console.log($('#chat').children('#messages').find('.tse-scroll-content')[0].scrollTop);
        
        position du scroll
        console.log($('#chat').children('#messages').find('.tse-scroll-content')[0].scrollHeight - $('#chat').children('#messages').find('.tse-scroll-content')[0].offsetHeight);
    */

    var scroll_start_stop = function(force){
        scroll_tab = $('#chat').children('#messages').find('.tse-scroll-content');
        if(force == "normale"){
            if(scrollemulator_modo){
                scroll_tab[0].scrollTop = scroll_tab[0].scrollTop - 1;
                $('#interface_modo_TrackpadScrollEmulator').text('Activer le Scroll');
                scrollemulator_modo = false;
                self.message_debug('Interface Modo : Scroll Stop');
            }else{
                scroll_tab[0].scrollTop = scroll_tab[0].scrollHeight;
                $('#interface_modo_TrackpadScrollEmulator').text('Desactiver le Scroll');
                scrollemulator_modo = true;
                self.message_debug('Interface Modo : Scroll Start');
            };
        }else if(force == "stop"){
            scroll_tab[0].scrollTop = scroll_tab[0].scrollTop - 1;
            scrollemulator_modo = false;
            self.message_debug('Interface Modo : Scroll Stop');
        }else if(force == "start"){
            scroll_tab[0].scrollTop = scroll_tab[0].scrollHeight;
            scrollemulator_modo = true;
            self.message_debug('Interface Modo : Scroll Start');
        };
    };

    $("#interface_modo_config_info").click( function() {
        if ($("#interface_modo_config").css("display") == "block") {
            $('#interface_modo_config').fadeOut('fast');
            $('#interface_modo_config_info').removeClass('show_streaminfo_active');
            self.message_debug('Interface Modo : remove');
            if(full_screen){
                $('.onethird').fadeIn('fast');
                scroll_start_stop("start");
            };
        }else{
            $('#interface_modo_config_info').addClass('show_streaminfo_active');
            $('#interface_modo_config').fadeIn('fast');
            self.message_debug('Interface Modo : add');
            if(full_screen){
                $('.onethird').fadeOut('fast');
            };
        };
    });
    
    $("#interface_modo_nouveau_csrf_token").click( function() {
        var ancient_csrf_token = $(document).find("#csrf_token").val();
        var thehtml = self.nouveau_token();
        var nouveau_csrf_token = $(thehtml).find("#csrf_token").val();
        self.message_debug('Interface Modo : \n Ancient : ' +ancient_csrf_token+ ' \n Nouveau : '+nouveau_csrf_token);
        $('#csrf_token').val(nouveau_csrf_token);
    });
};

this.nouveau_token = function() {
    var thedomain =  document.domain;
    var thehtml = jQuery.ajax({
        url: 'http://' + thedomain,
        async: false
    }).responseText;
    return thehtml;
};

$("#lines").bind("DOMNodeInserted", function(event){
    self.message_debug('Interface Modo : event message');
    //console.log(event);
	console.log(event.target);
    /*
    Object {messageInfos: Object}
        messageInfos: Object
            message: Object
                content: "...bla ...bla"
                id: "32548-8048926"
            user: Object
                gravatar_hash: "16b22951f2a9be079a7281bbf975c667"
                id: 32548
                level: 6
                name: "lolilol"
    */

    var data = $(event.target).data().messageInfos;
    if(typeof data !== 'undefined')
    {
        if(data.user.level == 6)
        {
            self.message_debug('Interface Modo : Message d\'un viewer');
            var scroll_tab = $('#chat').children('#messages').find('.tse-scroll-content');
            var avant_scroll_tab = ((scroll_tab[0].scrollHeight - scroll_tab[0].offsetHeight) - scroll_tab[0].scrollTop); // niveau du scroll avant l'ajout du bouton

            $('#message-'+data.message.id+' .message-author').before('<button type="button" class="close" id="interface_modo_supprimer_message">×</button>'); // ajout du bouton

            var apres_scroll_tab = ((scroll_tab[0].scrollHeight - scroll_tab[0].offsetHeight) - scroll_tab[0].scrollTop); // niveau du scroll apres l'ajout du bouton

            if(avant_scroll_tab == 0) // si le chat est au plus bas
            {
                if((apres_scroll_tab - avant_scroll_tab) > 0) // si apres l'ajout du bouton le scroll est modifier
                {
                    scroll_tab[0].scrollTop = scroll_tab[0].scrollHeight; // on scroll au plus bas
                    self.message_debug('Interface Modo : Erreur Scroll ' + (apres_scroll_tab - avant_scroll_tab));
                };
            };

        }else{
            self.message_debug('Interface Modo : Ce n\'est pas un viewer');
        };
    }else{
        self.message_debug('Interface Modo : Unknown message');
    };
});

this.commande_admin = function(commande_name, parameters) {
    $.ajax({
    type: "POST",
    url: admin_url,
    data: {
        action:
            commande_name,
        parameters:
            parameters,
        csrf_token:
            $('#csrf_token').val()
        },
    success: function(message) {
            if (message.success) {
                    self.message_debug('Interface Modo : Commande envoyée avec succès.');
                } else {
                    self.message_debug('Interface Modo : Une erreur est survenue : ' + message.error_message);
                }
        },
    error: function() {
            self.message_debug('Interface Modo :  Erreur de communication avec le serveur.');
            var thehtml = self.nouveau_token();
            var nouveau_csrf_token = $(thehtml).find("#csrf_token").val();
            $('#csrf_token').val(nouveau_csrf_token);
            self.commande_admin(commande_name, parameters);
        }
    });
};

var start = function()
{
    console.log('Interface Modo : Start');
    setTimeout(interface_moderateur, 1000);
};
start();